package com.wh.beans.tags;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.wh.beans.Toolbar;
import com.legend.security.PermissionConfig;
import com.legend.security.PermissionItem;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class OperateMenu implements TemplateDirectiveModel {

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException,
			IOException {
		try {
			String moduleCode = params.get("moduleCode").toString();
			PermissionConfig config = new PermissionConfig();
			List<PermissionItem> lst = config.getPermissionItems(moduleCode);
			if (lst == null || lst.size() == 0) {
				env.getOut().write("未配置操作权限项");
			} else {
				StringBuffer sb = new StringBuffer();
				sb.append("<script type='text/javascript'>");
				sb.append(MessageFormat.format("function getOperate_{0}(id,row,index)",moduleCode));
				sb.append("{var menubarStr='';");
				for (PermissionItem p : lst) {
					if ((p.getPosition() & 2) == 2) {
						String str="menubarStr+='<a href=\"javascript:void(0);\" onclick=\"" + MessageFormat.format(p.getEvent(),"\\''+id+'\\'","'+index+'")  + "\" class=\"menubtn\"><i class=\""+p.getIconCls()+"\"></i>" + p.getName() + "</a>';";
                        str=str.replace("[module]",moduleCode);
                        sb.append(str);

                    }
				}
				sb.append("return menubarStr;}");
				sb.append("</script>");
				env.getOut().write(sb.toString());
			}

		} catch (RuntimeException e) {
			env.getOut().write(e.getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			env.getOut().write(e.getMessage());
		}

	}

}
